package top.anonyeast.controller;

import org.springframework.web.bind.annotation.*;
import top.anonyeast.pojo.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    List<User> userList = new ArrayList<>();
    int initId = 1005;

    UserController() {
        userList.add(new User(1001, "张三", "男", 11));
        userList.add(new User(1002, "李四", "女", 12));
        userList.add(new User(1003, "王五", "男", 13));
        userList.add(new User(1004, "赵六", "女", 14));
    }

    /**
     * 查找所有
     * @return
     */
    @GetMapping("/findAll")
    public List<User> findAll() {
        return userList;
    }

    /**
     * 通过id查找
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public User findById(@PathVariable int userId){
        for (User user : userList) {
            if (user.getId() == userId){
                return user;
            }
        }
        return null;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Map<String, String> add(@RequestBody User user) {
        userList.add(new User(initId, user.getName(), user.getGender(), user.getAge()));
        System.out.println(userList);
        initId++;
        Map<String, String> map = new HashMap<>();
        map.put("success", "true");
        if (user.getName() == null) {
            map.put("msg", "添加失败");
        } else {
            map.put("msg", "添加成功");
        }
        return map;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{userId}")
    public Map<String, String> delete(@PathVariable("userId") int id) {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            if (user.getId() == id){
                userList.remove(i);
                map.put("success","true");
                map.put("msg","删除成功");
                return map;
            }
        }
        map.put("success","false");
        map.put("msg","删除失败");
        return map;
    }

    /**
     * 编辑用户信息
     * @param updateUser
     * @return
     */
    @PutMapping
    public Map<String, String> update(@RequestBody User updateUser){
        Map<String, String> map = new HashMap<>();
        Integer userId = updateUser.getId();
        for (User user : userList) {
            if (user.getId().equals(userId)){
                user.setName(updateUser.getName());
                user.setAge(updateUser.getAge());
                user.setGender(updateUser.getGender());
                map.put("success","true");
                map.put("msg", "修改成功");
                return map;
            }
        }
        map.put("success","false");
        map.put("msg", "修改失败");
        return map;
    }
}
